package com.sec.etech.security.service;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Assert;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;

import java.util.Date;


@Slf4j
public class JwtUtil {

    // load from env
    static class JwtProps{
        String secret = "asd%WE^@&fas156dfa";
        String issuer = "openBPM";
    }

    private static JwtProps jwtPros = new JwtProps();

    /**
     * 生成token
     *
     * @param username 用户
     * @param audience 终端
     * @param exp      有效期(单位秒) 0:不过期
     * @return
     */
    public static String generateToken(String username, String audience, int exp) {
        Assert.notBlank(audience, "生成token 签发对象 不能为空", new Object[0]);

        String token = null;
        JwtBuilder builder = Jwts.builder().setIssuer(jwtPros.issuer).setSubject(username).setAudience(audience).setIssuedAt(new Date()).signWith(SignatureAlgorithm.HS512, jwtPros.secret);
        if (exp != 0) {
            builder.setExpiration(DateUtil.offset(new Date(), DateField.SECOND, exp));
        }
        token = builder.compact();
        return token;
    }

    private static Claims getClaimsFromToken(String token) {
        // jjwt 0.9.1
        return (Claims) Jwts.parser().setSigningKey(jwtPros.secret).parseClaimsJws(token).getBody();
    }

    public static String getValidSubjectFromRedisToken(String authToken) {
        if (StringUtils.isEmpty(authToken) || !authToken.startsWith("eyJh")) {
            return null;
        }
        try {
            Claims claims = getClaimsFromToken(authToken);
            if (claims != null) {
                String subject = claims.getSubject();
                //String audience = claims.getAudience();
                return subject;
            }
        } catch (Exception var4) {

        }
        return null;
    }

}
